package com.example.java.sink;

import org.apache.flink.api.common.functions.MapFunction;
import org.apache.flink.api.java.tuple.Tuple2;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.redis.RedisSink;
import org.apache.flink.streaming.connectors.redis.common.config.FlinkJedisPoolConfig;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommand;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisCommandDescription;
import org.apache.flink.streaming.connectors.redis.common.mapper.RedisMapper;
import org.apache.log4j.Logger;

public class SinkToRedisMain {
//    private static Logger log = Logger.getLogger(Log4j .class);
    private static Logger logger = Logger.getLogger(SinkToRedisMain.class);
    // <Tuple2<String,String>>泛型是要sink的dataStream的类型
    private static class MyRedisMapper implements RedisMapper<Tuple2<String, String>> {
        // 要以哪种命令向redis中插入数据
        @Override
        public RedisCommandDescription getCommandDescription() {
            return new RedisCommandDescription(RedisCommand.SET);
        }

        @Override
        public String getKeyFromData(Tuple2<String, String> data) {
            System.out.println("key: " + data.f0);
            return data.f0;
        }

        @Override
        public String getValueFromData(Tuple2<String, String> data) {
            System.out.println("value: " + data.f1);
            return data.f1;
        }
    }


    public static void main(String[] args) throws Exception {
        logger.error("test");
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        DataStreamSource<String> data = env.socketTextStream("linux121", 8888);
        SingleOutputStreamOperator<Tuple2<String, String>> mappedData =
                data.map(new MapFunction<String, Tuple2<String, String>>() {
            @Override
            public Tuple2<String, String> map(String value) throws Exception {
                return new Tuple2<>("names", value);
            }
        });

        FlinkJedisPoolConfig config = new FlinkJedisPoolConfig.Builder()
                .setHost("linux122")
                .setPort(6379)
                .build();

        RedisSink<Tuple2<String, String>> redisSink = new RedisSink<>(config, new MyRedisMapper());
        mappedData.print();
        mappedData.addSink(redisSink);
        env.execute();
    }
}
